<template>
  <km-layout>

    <template v-slot:page>
      <q-input ref="title" v-on:blur="updateContent" borderless placeholder="请输入标题" class="title-edit" v-model='title'/>
      <q-no-ssr>
        <wang-editor ref='editor' v-model="content" plain/>
      </q-no-ssr>
    </template>

    <template v-slot:control>
      <div class="row justify-between toolbar">
        <q-item clickable @click="handlePost">
          <q-item-section avatar>
            <q-avatar class='q-px-xs' color="secondary" text-color="white" icon="local_activity"/>
          </q-item-section>
          <q-item-section>发布</q-item-section>
        </q-item>
        <q-item clickable @click="$router.go(-1)">
          <q-item-section avatar>
            <q-avatar class='q-px-xs' color="grey-4" text-color="grey-10" icon="arrow_back"/>
          </q-item-section>
          <q-item-section>返回</q-item-section>
        </q-item>
        <q-item clickable @click="handleDeleteDraft">
          <q-item-section class='q-px-none' avatar>
            <q-avatar class='q-px-none' avatar size='36px' color="grey-4" text-color="grey-10" icon="close"/>
          </q-item-section>
          <q-item-section>废弃草稿</q-item-section>
        </q-item>
      </div>
      <!-- <div class="draft"> {{ draft }}</div> -->
      <div class="attrs">
        <q-input ref="parent" dense filled v-model="parent" placeholder="1、输入父级id，点击左侧要选择的菜单在地址栏复制id"/>
      </div>
      <div class="attrs">
        <q-input dense filled v-model="seq" placeholder="在同级中的顺序"/>
      </div>
      <div class="attrs">
        <q-input type='textarea' dense filled v-model="tags" placeholder="回车换行输入新标签"/>
      </div>
    </template>
  </km-layout>
</template>
<script>
import { defineAsyncComponent, defineComponent } from 'vue'
import iContent from 'src/api/content'
// import iArticle from 'src/api/content'
import KmLayout from 'src/layouts/KmLayout.vue'
import AppActivityMixin from 'src/mixins/app-activity'

export default defineComponent({
  mixins: [AppActivityMixin],
  components: {
    KmLayout,
    WangEditor: defineAsyncComponent(() => import('src/components/wangEditor/WangEditor.vue'))
  },
  data () {
    return {
      id: '',
      title: '',
      content: '',
      lastEditTime: Date.now(),
      draft: '',
      parent: '',
      seq: '',
      level: '',
      tags: '',
      kmSpaceId: ''
    }
  },
  watch: {
    content () {
      this.updateContent()
    }
  },
  async mounted () {
    if (this.$route.params.action === 'create') {
      console.log('create')
      this.parent = this.$route.params.parent
      this.kmSpaceId = this.$route.params.kmSpaceId
    } else if (this.$route.params.action === 'edit') {
      console.log('edit')
      this.getArticle(this.$route.query.id)
    }
    this.$refs.title.focus()
  },
  unmounted () {
    // window.removeEventListener('beforeunload', this.updateContent)
  },
  methods: {
    async handleDeleteDraft () {
      const content = {
        _id: this.id,
        draft: ''
      }
      const res = await iContent.update(content)
      if (res.ok === 1) {
        this.$router.go(-1)
      }
    },
    async getArticle (id) {
      // console.log('getArticle', query)
      const data = await iContent.findContents({ id: id })
      console.log('getArticle', data)
      if (data) {
        this.id = data._id
        this.title = data.title
        this.parent = data.parentId
        this.kmSpaceId = data.kmSpaceId
        if (data.tags && data.tags.length > 0) this.tags = data.tags.join('\n')
        if (data.draft && data.draft.length > 0) {
          this.content = data.draft
        } else {
          this.content = data.content
        }
        this.seq = data.seq
      }
    },
    async createContent () {
      const data = await iContent.create({
        title: this.title,
        draft: this.content,
        content: this.content,
        parentId: this.parent,
        kmSpaceId: this.kmSpaceId,
        status: 1,
        type: 1
      })
      console.log('data', data)
      this.id = data._id
      await this.getArticle(this.id)
    },
    async updateContent () {
      // 距上次6s未编辑则自动保存
      // 6s内则返回，继续等待
      // if (!this.id || (Date.now() - this.lastEditTime <= 6 * 1000)) return
      // this.lastEditTime = Date.now()
      if (this.id === '') {
        if (this.title === '' && this.content === '' && this.draft === '') return
        await this.createContent()
      }
      const content = {
        _id: this.id,
        seq: this.seq,
        title: this.title,
        draft: this.content,
        parentId: this.parent,
        tags: this.tags.split('\n').filter(i => i !== '')
      }
      const res = await iContent.update(content)
      console.log('res', res)
      if (res.ok === 1) {
        this.draft = '草稿已保存'
        this.$store.dispatch('km/initMenu', { kmSpaceId: this.kmSpaceId })
      }
    },
    async logVisit () {
      await this.log()
    },
    async handlePost () {
      setTimeout(() => {
        // 等blur执行完，故延迟一会儿
        this.post()
      }, 300)
    },
    async post () {
      console.log('handlePost')
      if (this.title.length === 0) {
        this.$q.notify({
          icon: 'insert_emoticon',
          message: '请输入标题',
          color: 'warning',
          position: 'top',
          timeout: 1000
        })
        this.$refs.title.focus()
        return
      }
      const content = {
        _id: this.id,
        status: 6,
        seq: this.seq,
        title: this.title,
        draft: '',
        content: this.content,
        parentId: this.parent,
        tags: this.tags.split('\n').filter(i => i !== '')
      }
      const res = await iContent.update(content)
      if (res.ok === 1) {
        this.$router.push({
          path: '/km/article',
          query: { id: this.id }
        })
      }
    }
  }
})
</script>

<style lang="scss">
.draft {
  color: $nonce;
  line-height: 1;
}

.title-edit {
  color: #222222;
  font-weight: bolder;
  margin: 0;
  font-size: 32px;
  line-height: 1.4;
  letter-spacing: .034em;
  font-family: PingFang SC, Microsoft YaHei, -apple-system, BlinkMacSystemFont, Helvetica Neue, Source Han Sans SC, Noto Sans CJK SC, WenQuanYi Micro Hei, sans-serif;
  word-wrap: break-word;
  hyphens: auto;
  padding: 0;
  outline: 0;
}

.title-edit input {
  // 与下方对齐
  padding-left: 10px;
}

.attrs {
  margin-bottom: 5px;
}
</style>
